package com.bmatch.tech.service.impl;

import com.bmatch.tech.service.UploadService;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @program:FileStore
 * @author:LinJinhao
 * @create:2018-12-01 12:25
 **/
@MultipartConfig
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet implements UploadService {

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {

        String path = ApplyPath+"222.jpg";
        //得到文件的输入流
        FileInputStream in = new FileInputStream(path);

        int len = 1;
        byte[] b = new byte[1024];

        String filename = path.substring(path.lastIndexOf("/") + 1);

        //设置文件名的编码
        if (request.getHeader("user-agent").toLowerCase().contains("msie")){
            filename = URLEncoder.encode(filename,"UTF-8");
        }else{
            filename = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        }
        //告知浏览器要下载文件，如果没有这个，浏览器会直接把图片显示到页面上
        response.setHeader("content-disposition","attachment;filename="+filename);

        //根据文件名自动获得文件类型
        response.setContentType(this.getServletContext().getMimeType(filename));

        //使用response输出流输出图片
        ServletOutputStream out = response.getOutputStream();
        while ((len = in.read(b)) != -1){
            out.write(b,0,len);
        }
        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
